package com.tfjybj.itoo.teach.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.dmsdbj.itoo.tool.constantutil.YearSemester;
import com.dmsdbj.itoo.tool.tenancy.TenancyContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.StudentTeachClassEntity;
import com.tfjybj.itoo.teach.model.StudentModel;
import com.tfjybj.itoo.teach.model.StudentTeachClassModel;
import com.tfjybj.itoo.teach.model.TeacherTeachClassModel;
import com.tfjybj.itoo.teach.provider.dao.StudentTeachClassDao;
import com.tfjybj.itoo.teach.provider.service.StudentService;
import com.tfjybj.itoo.teach.provider.service.StudentTeachClassService;
import com.tfjybj.itoo.teach.template.StudentTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

import static com.tfjybj.itoo.teach.provider.until.DemoConstants.*;

/**
 * StudentTeachClassService接口实现类
 * ${base}表
 *
 * @author 田成荣
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Service("studentTeachClassService")
@Slf4j
public class StudentTeachClassServiceImpl extends BaseServicePlusImpl<StudentTeachClassDao, StudentTeachClassEntity> implements StudentTeachClassService {

    //region 模板生成

    @Resource
    private StudentTeachClassDao studentTeachClassDao;

    @Resource
    private StudentService studentService;


    @Resource
    private StudentTeachClassService studentTeachClassService;

    @Resource
    private RedisTemplate<String, StudentTemplate> redisTemplate;


    @Override
    public PageInfo<StudentTeachClassEntity> queryByLikeStudentId(String studentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(studentTeachClassDao.queryLikeStudentId(studentId));
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    @Override
    public int deleteStudentTeachClass(List<String> studentIds, String teachClassId, String operator){
        return studentTeachClassDao.deleteStudentTeachClass(studentIds,teachClassId,operator);
    }


    @Override
    public boolean deleteSingleStudentTeachClass(String studentId, String teachClassId, String operator){
        String id=studentTeachClassService.queryIdByStudentIdAndteachClassId(studentId,teachClassId);
        return studentTeachClassService.removeById(id);
    }



    @Override
    public List<String> findTeachClassIdsByStudentId(String studentId){
        return studentTeachClassDao.findTeachClassIdsByStudentId(studentId);
    }


    @Override
    public List<String> querycourseIDBystudentid(String studentId){
        String schoolyear = YearSemester.getYearSemesterCode(1, 1).get(0);//获得下一个学期
        return studentTeachClassDao.querycourseIDBystudentid(studentId,schoolyear);
    }


    @Override
    public Boolean deleteStudentTeachClassbyId(String studentId,String teachClassId) {
        StudentTeachClassModel model=new StudentTeachClassModel();
        String operator= TenancyContext.UserID.get();
        model.setTeachClassId(teachClassId);
        model.setStudentId(studentId);
        Boolean flag=false;
        if(studentTeachClassDao.deleteStudentTeachClassbyId(model,operator)>0){
            flag=true;
        }
        return flag;
    }
    @Override
    public PageInfo<StudentModel>  queryTeachClassStudentInfoByNameStrLike(String strLike, String teachClassId, Integer pageNum, Integer pageSize){
        strLike=strLike.trim();
        teachClassId=teachClassId.trim();
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(studentTeachClassDao.queryTeachClassStudentInfoByNameStrLike(strLike,teachClassId));
    }

    @Override
    public boolean createBystudentid(String studentId, String teachClassId) {
        StudentTeachClassEntity studentTeachClassEntity = new StudentTeachClassEntity();
        studentTeachClassEntity.setStudentId(studentId);
        studentTeachClassEntity.setTeachClassId(teachClassId);
        studentTeachClassEntity.setId(IdWorker.getIdStr());
        studentTeachClassEntity.setOperator(TenancyContext.UserID.get());
        return this.save(studentTeachClassEntity);
    }


    @Override
    public PageInfo<StudentModel>queryTeachClassStudentInfoByNameAndCodeStrLike(String studentName,String studentCode,String teachClassId,Integer pageNum,Integer pageSize){
        studentName=studentName.trim();
        teachClassId=teachClassId.trim();
        PageHelper.startPage(pageNum, pageSize);
        studentCode=studentCode.trim();
        return new PageInfo<>(studentTeachClassDao.queryTeachClassStudentInfoByNameAndCodeStrLike(studentName,studentCode,teachClassId));
    }


    @Override
    public boolean downLoadStudentTeachClassTemplate (HttpServletResponse response){
        Map<Serializable, Serializable> map = new HashMap<>(16);
        List<StudentTemplate> templateList = new ArrayList<>();
        StudentTemplate studentTemplate = new StudentTemplate();

        //添加下载模板范例
        studentTemplate.setCode("11010531054");
        studentTemplate.setName("杨赛男");


        templateList.add(studentTemplate);

        //sheet的名字
        map.put(SHEET_NAME, "上课班-学生管理表");
        //需要导入的字段
        map.put(COLUMNS, new String[]{"code","name"});
        //表格的标题
        map.put(TITLE, "上课班-学生管理表");
        map.put(NAME, "上课班-学生管理表");
        map.put(DATA_LIST, (Serializable) templateList);
        try {
            ExcelUtil.exportExcel(map, response);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public ItooResult importStudentTeachClassByTemplate(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response, String teachClassId){
        response.setContentType("UTF-8");

        try {
            //校验文件是否存在
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                log.error("导入失败,fileName is null!");
                return ItooResult.build(ItooResult.FAIL, "传入的文件为空！");
            }

            //EXCEL解析成List
            Map<Serializable, Serializable> map = new HashMap<>(4);
            map.put(SHEET_NAME, "上课班-学生管理表");
            map.put(CLASS, StudentTemplate.class);
            List<StudentTemplate> studentTemplateList = ExcelUtil.importExcel(Objects.requireNonNull(fileName), map, request, response);

            if (studentTemplateList.size() == 0) {
                return ItooResult.build(ItooResult.FAIL, "导入的数据为空，请填写！");
            }
            //定义导入的错误数据集合并存redis中形式的<String,studentTemplateTemplate>
            List<StudentTemplate> errorTPTList = new ArrayList<>();
            String errorTPTListId = IdWorker.getIdStr();
            Long size = redisTemplate.opsForZSet().size(errorTPTListId);
            size = size == null ? 0L : size;

            for (StudentTemplate excelTPT : studentTemplateList) {

                if (!this.verify(excelTPT,teachClassId)) {
                    StudentTemplate studentTemplateT = new StudentTemplate();
                    BeanUtils.copyProperties(excelTPT, studentTemplateT);

                    errorTPTList.add(studentTemplateT);
                    redisTemplate.opsForZSet().add(errorTPTListId, studentTemplateT, size + 1);
                    continue;
                }

                StudentTeachClassEntity studentTeachClassEntity = insertValue(excelTPT,teachClassId);
                this.save(studentTeachClassEntity);
            }
            //不符合条件的信息返回
            if (errorTPTList.size() > 0) {
                return ItooResult.build("0001","部分导入失败",errorTPTListId);
            }
        }
        catch(Exception e)
        {
            return ItooResult.build(ItooResult.FAIL, "导入数据异常！",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导入数据成功！");
    }

    private StudentTeachClassEntity insertValue(StudentTemplate studentTemplate, String teachClassId){
        StudentTeachClassEntity studentTeachClassEntity = new StudentTeachClassEntity();
        //将导入内容放到entity中对应的属性中去
        BeanUtils.copyProperties(studentTemplate, studentTeachClassEntity);
        String studentID=studentService.queryStudentByCode(studentTemplate.getCode()).get(0).getId();
        studentTeachClassEntity.setId(IdWorker.getIdStr());
        studentTeachClassEntity.setTeachClassId(teachClassId);
        studentTeachClassEntity.setStudentId(studentID);
        studentTeachClassEntity.setIsDelete(0);
        studentTeachClassEntity.setOperator("大米时代");
    return studentTeachClassEntity;
    }




    private boolean verify (StudentTemplate excelTPT, String teachClassId )
    {
        if (StringUtils.isEmpty(excelTPT.getCode())) {
            excelTPT.setFailReason("学生代码未填写");
            log.warn("导入失败,学生代码未填写,excelFooEntity-{}", excelTPT);
            return false;
        }

        if (StringUtils.isEmpty(excelTPT.getName())) {
            excelTPT.setFailReason("学生名称未填写");
            log.warn("导入失败,学生名称未填写,excelFooEntity-{}", excelTPT);
            return false;
        }

        StudentTeachClassEntity studentTeachClassEntity = new StudentTeachClassEntity();

        //将导入内容放到entity中对应的属性中去
        BeanUtils.copyProperties(excelTPT, studentTeachClassEntity);

        //上课班-学生管理表
        studentTeachClassEntity.setId(IdWorker.getIdStr());

        //未删除
        studentTeachClassEntity.setIsDelete(0);

        //操作员
        studentTeachClassEntity.setOperator("大米时代");

        //通过学生code获取学生信息
        List<StudentModel> studentModels = studentService.queryStudentByCode(excelTPT.getCode());
        if (CollectionUtils.isEmpty(studentModels)){
            excelTPT.setFailReason("找不到学生code：" + excelTPT.getCode());
            log.warn("找不到学生code：" + excelTPT.getCode()  + "不能添加-",excelTPT);
            return false;
        }
        studentTeachClassEntity.setStudentId(studentModels.get(0).getId());



        //判断查询出的课程名称与导入时写入的课程名称是否相同
        if (!studentModels.get(0).getName().equals(excelTPT.getName())){
            excelTPT.setFailReason("学生代码：" + excelTPT.getCode() + "所对应的学生名称与输入的学生名称：" + excelTPT.getName() + "不匹配,不能添加");
            log.warn("学生代码：" + excelTPT.getCode() + "所对应的学生名称与输入的学生名称：" + excelTPT.getName() + "不匹配,不能添加",excelTPT);
            return false;
        }

        //学生ID
        studentTeachClassEntity.setStudentId(studentModels.get(0).getId());

        //上课班id
        studentTeachClassEntity.setTeachClassId(teachClassId);


        //判断上课班-学生管理表是否已经存在
        String idIsExist = studentTeachClassService.findIdIsExist(studentModels.get(0).getId(),teachClassId);
        if (!StringUtils.isEmpty(idIsExist)){
            excelTPT.setFailReason("学生代码：" + excelTPT.getCode() + "学生姓名：" + excelTPT.getName() + "已存在对应的上课班-学生管理表，不能重复添加");
            log.warn("学生代码：" + excelTPT.getCode() + "学生姓名：" + excelTPT.getName() + "已存在对应的上课班-学生管理表，不能重复添加",excelTPT);
            return false;
        }
        return true;
    }

    @Override
    public String findIdIsExist(String studentId,String teachClassId){
        return studentTeachClassDao.findIdIsExist( studentId, teachClassId);
    }


    @Override
    public Boolean checkByStudentCode(String studentId) {
        Boolean studentcount=false;
        if(studentTeachClassDao.checkByStudentCode(studentId)>0){
            studentcount=true;
        }
        return studentcount;
    }

    @Override
    public boolean downErrorList(String errorListId, HttpServletResponse response) {
        // redis 取出没有成功导入的人员信息
        Set set = redisTemplate.opsForZSet().range(errorListId, 0, -1);
        ArrayList studentTemplate = new ArrayList<>(set);
        // 清空redis数据
        redisTemplate.delete(errorListId);

        //导出
        if (studentTemplate.size() == 0) {
            return false;
        }
        Map<Serializable, Serializable> errorMap = new HashMap<>(16);
        //sheet的名字
        errorMap.put(SHEET_NAME, "上课班-学生管理表");
        //需要导入的字段
        errorMap.put(COLUMNS, new String[]{"code","name","failReason"});
        //表格的标题
        errorMap.put(TITLE, "上课班-学生管理表");
        errorMap.put(NAME, "上课班-学生管理表");
        errorMap.put(DATA_LIST, (Serializable) studentTemplate);

        try {
            ExcelUtil.exportExcel(errorMap, response);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    @Override
    public String queryIdByStudentIdAndteachClassId(String studentId,String teachClassId){
        return studentTeachClassDao.queryIdByStudentIdAndteachClassId(studentId,teachClassId);
    }


    @Override
    public boolean createByStudentidAndTeachClassIds(String studentId,List<String>teachClassIds){

        StudentTeachClassModel studentTeachClassModel=new StudentTeachClassModel();
        for(String teachClassId: teachClassIds){
            studentTeachClassModel.setStudentId(studentId);
            studentTeachClassModel.setTeachClassId(teachClassId);
            String id=studentTeachClassService.queryIdByStudentIdAndteachClassId( studentId, teachClassId);
            if (!StringUtils.isEmpty(id)){
                log.warn("学生ID：" + studentTeachClassModel.getStudentId() + "上课班ID：" + studentTeachClassModel.getTeachClassId() + "已匹配,请重新输入!");
                return false;
            }
            boolean result= studentTeachClassService.createBystudentid(studentTeachClassModel.getStudentId(),studentTeachClassModel.getTeachClassId());
            if(!result){
                log.warn("学生ID：" + studentTeachClassModel.getStudentId() + "上课班ID：" + studentTeachClassModel.getTeachClassId() + "添加失败");
                return false;
            }
        }
        return true;
    }

    /**
     * 根据上课班id查询学生信息
     * @param teachClassId
     * @return 学生姓名list
     * @author 郝雨烁
     * @since 0.0.1 2019年3月6日16:34:48
     */
    @Override
    public List<TeacherTeachClassModel> queryStudents(String teachClassId){
        return studentTeachClassDao.queryStudents(teachClassId);
    }

    /**
     * 根据上课班id和学生id删除这个学生
     * @param teachClassId
     * @param studentId
     * @return
     * @author 郝雨烁
     * @since 0.0.1 2019年3月7日21:33:41
     */
    @Override
    public boolean deleteStudentInGroups(String teachClassId, String studentId){
        // 1.根据上课班id和学生id查询这条数据
      StudentTeachClassEntity studentTeachClassEntity =  studentTeachClassDao.findByTeachClassIdAndStudentId(teachClassId,studentId);
        if(StringUtils.isEmpty(studentTeachClassEntity)){
            return false;
        }else{
            // 2.更新这条数据
            StudentTeachClassEntity teachClassEntity = new StudentTeachClassEntity();
            teachClassEntity.setIsDelete(1);
            this.updateById(teachClassEntity);
            return true;
        }

    }

}
